package multi_thread.advanced;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author Cheng Jun
 * Description: 获取 Unsafe 类的 theUnsafe对象
 * @version 1.0
 * @date 2021/9/29 19:54
 */
public class UnsafeUtil {

    /**
     * 获取 Unsafe 类的 theUnsafe对象
     *
     * @return sun.misc.Unsafe
     * @author Cheng Jun
     * @date 2021/9/29 19:57
     */
    public static Unsafe theUnsafe() {
        // 获取Unsafe 的 theUnsafe 类变量
        try {
            Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
            // 突破 private 限制
            unsafeField.setAccessible(true);
            // 如果字段是静态字段的话，传入任何对象都是可以的，包括null
            return (Unsafe) unsafeField.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
